<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

if (!defined('__ROOT__')) {
    $_root = rtrim(dirname(rtrim($_SERVER['SCRIPT_NAME'], '/')), '/');
    define('__ROOT__', (('/' == $_root || '\\' == $_root) ? '' : $_root));
}
use \think\Db;
use \think\Loader;
// 应用公共文件
/**
 * 获取ip
 * @dateTime 2016-05-12T17:39:35+0800
 * @return   [type]                   [description]
 */
function inge_get_ip()
{
    if (getenv('HTTP_CLIENT_IP')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } else if (getenv('HTTP_X_FORWARDED_FOR')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } else if (getenv('REMOTE_ADDR')) {
        $ip = getenv('REMOTE_ADDR');
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
/**
 * 获取浏览器
 */
function inge_get_browser()
{
    $agent = $_SERVER["HTTP_USER_AGENT"];
    if (strpos($agent, 'MSIE') !== false || strpos($agent, 'rv:11.0')) //ie11判断
    {
        return "ie";
    } else if (strpos($agent, 'Firefox') !== false) {
        return "firefox";
    } else if (strpos($agent, 'Chrome') !== false) {
        return "chrome";
    } else if (strpos($agent, 'Opera') !== false) {
        return 'opera';
    } else if ((strpos($agent, 'Chrome') == false) && strpos($agent, 'Safari') !== false) {
        return 'safari';
    } else if (strpos($agent, 'MicroMessenger') !== false) {
        return 'weixin';
    } else {
        return 'unknown';
    }

}

/**
 * 获取浏览器版本号
 * @dateTime 2016-05-12T17:41:31+0800
 * @return   [type]                   [description]
 */
function inge_get_browser_ver()
{
    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        //当浏览器没有发送访问者的信息的时候
        return 'unknow';
    }
    $agent = $_SERVER['HTTP_USER_AGENT'];
    if (preg_match('/MSIE\s(\d+)\..*/i', $agent, $regs)) {
        return $regs[1];
    } elseif (preg_match('/FireFox\/(\d+)\..*/i', $agent, $regs)) {
        return $regs[1];
    } elseif (preg_match('/Opera[\s|\/](\d+)\..*/i', $agent, $regs)) {
        return $regs[1];
    } elseif (preg_match('/Chrome\/(\d+)\..*/i', $agent, $regs)) {
        return $regs[1];
    } elseif ((strpos($agent, 'Chrome') == false) && preg_match('/Safari\/(\d+)\..*$/i', $agent, $regs)) {
        return $regs[1];
    } else {
        return 'unknow';
    }

}
/**
 * 获取用户系统
 * @dateTime 2016-05-12T17:39:48+0800
 * @return   [type]                   [description]
 */
function inge_get_os()
{
    $agent = $_SERVER['HTTP_USER_AGENT'];
    $os    = false;
    // var_dump($agent);
    if (preg_match('/win/i', $agent) && strpos($agent, '95')) {
        $os = 'Windows 95';
    } else if (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90')) {
        $os = 'Windows ME';
    } else if (preg_match('/win/i', $agent) && preg_match('/98/i', $agent)) {
        $os = 'Windows 98';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent)) {
        $os = 'Windows Vista';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent)) {
        $os = 'Windows 7';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent)) {
        $os = 'Windows 8';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent)) {
        $os = 'Windows 10';
        #添加win10判断
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent)) {
        $os = 'Windows XP';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent)) {
        $os = 'Windows 2000';
    } else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent)) {
        $os = 'Windows NT';
    } else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent)) {
        $os = 'Windows 32';
    } else if (preg_match('/linux/i', $agent)) {
        $os = 'Linux';
    } else if (preg_match('/unix/i', $agent)) {
        $os = 'Unix';
    } else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent)) {
        $os = 'SunOS';
    } else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent)) {
        $os = 'IBM OS/2';
    } else if (preg_match('/Mac/i', $agent)) {
        $os = 'Mac OS';
    } else if (preg_match('/PowerPC/i', $agent)) {
        $os = 'PowerPC';
    } else if (preg_match('/AIX/i', $agent)) {
        $os = 'AIX';
    } else if (preg_match('/HPUX/i', $agent)) {
        $os = 'HPUX';
    } else if (preg_match('/NetBSD/i', $agent)) {
        $os = 'NetBSD';
    } else if (preg_match('/BSD/i', $agent)) {
        $os = 'BSD';
    } else if (preg_match('/OSF1/i', $agent)) {
        $os = 'OSF1';
    } else if (preg_match('/IRIX/i', $agent)) {
        $os = 'IRIX';
    } else if (preg_match('/FreeBSD/i', $agent)) {
        $os = 'FreeBSD';
    } else if (preg_match('/teleport/i', $agent)) {
        $os = 'teleport';
    } else if (preg_match('/flashget/i', $agent)) {
        $os = 'flashget';
    } else if (preg_match('/webzip/i', $agent)) {
        $os = 'webzip';
    } else if (preg_match('/offline/i', $agent)) {
        $os = 'offline';
    } else {
        $os = 'unknow';
    }
    return $os;
}

/**
 * 传入密码和随机数进行加密
 * @param $pwd 传入密码
 * @param $str  传入随机数
 * @return string 返回加密过后的密码
 */
function inge_encryption_pwd($pwd, $str)
{
    $newStr = md5($pwd . $str);
    $newStr = substr($newStr, 6);
    $newStr = md5($newStr . $str);
    $newStr = crypt($newStr, $str);
    return $newStr;
}

/**
 * 获取随机字符
 * @param $len 需要的长度
 * @param type 为1 则大小写字母都可以  为0则为数字
 * @return string 返回获取到的随机字符串
 *
 */
function inge_get_random_str($len = 10, $type = '1')
{
    $str = null;
    if ($type == '1') {
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    } else {
        $strPol = "0123456789";
    }
    $max = strlen($strPol) - 1;
    for ($i = 0; $i < $len; $i++) {
        $str .= $strPol[rand(0, $max)];
    }
    return $str;
}

/**
 * 验证是否是手机号
 * @param $mobilephone
 * @return bool
 */
function okay_ismobile($mobilephone)
{
    if (preg_match("/^1[0-9]{2}[0-9]{8}$|17[017]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|18[019]{1}[0-9]{8}$/", $mobilephone)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 验证是否为邮箱
 * @param  [type] $email [description]
 * @return [type]        [description]
 */
function okay_isemail($email)
{
    $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
//    if (preg_match("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+", $email)) {
    if (preg_match($pattern, $email)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 提取表单中的数据
 */
function select_object($fields) {
    $fields = explode(",", $fields);
    $_form = input('');
    $ret = [];
    foreach($fields as $f) {
        $ret[$f] = isset($_form[$f])?$_form[$f]:"";
    }
    return $ret;
}

/**
 *修饰Query
 */
function decorate_query($query, $wheres, $_form) {
    foreach($wheres as $where) {
        if(isset($_form[$where[0]]) && ($_form[$where[0]] != "")) {
            if(isset($where[1])) {
                if($where[1] == "like") {
                    $query->where($where[0],"like","%{$_form[$where[0]]}%");
                }else if(isset($where[2])){
                    $query->where($where[0],$where[1],$_form[$where[2]]);
                }else {
                    $query->where($where[0],$where[1],$_form[$where[0]]);
                }
            }else {
                $query->where($where[0],$_form[$where[0]]);
            }
        }
    }
}

function single_img($type=1,$file='',$width=600,$height=600,$watermark='./public/common/img/logo.png',$word='www.bcahz.com',$url=''){
    if($file){
        if($url == ''){
            $url = date("Ymd");
        }
        // 读取图片
        $image = \think\Image::open($file);
        // 图片处理
        switch ($type) {
            case 1: // 图片裁剪
                $image->crop($width, $height);
                break;
            case 2: // 缩略图
                $image->thumb($width, $width/$image->width()*$image->height(), \think\Image::THUMB_CENTER);
                break;
            case 3: // 垂直翻转
                $image->flip();
                break;
            case 4: // 水平翻转
                $image->flip(\think\Image::FLIP_Y);
                break;
            case 5: // 图片旋转
                $image->rotate();
                break;
            case 6: // 图片水印
                $image->water($watermark, \think\Image::WATER_NORTHWEST, 50);
                break;
            case 7: // 文字水印
                $image->text($word, VENDOR_PATH . 'topthink/think-captcha/assets/ttfs/HYQingKongTiJ.ttf', 20, '#refeee');
                break;
        }
// 保存图片（以当前时间戳）
// /public/uploads/ 可以用config.get()进行设置, 这样的话, 不管oss或者本地图片路径都可以解决.
        $saveName = request()->time().randomkeys(6) . '.png';
        if(!file_exists( 'uploads/'.$url)){
            mkdir( 'uploads/'.$url,0777,true);
        }
        $image->save( 'uploads/'.$url.'/' . $saveName);
    } else {
        return false;
    }
    $basename = \think\Request::instance()->root();

    if (pathinfo($basename, PATHINFO_EXTENSION) == 'php') {

        $basename = dirname($basename);

    }
    return $basename.'/uploads/'.$url.'/' . $saveName;
}

function randomkeys($length)
{
    $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ,./&lt;>?;#:@~[]{}-_=+)(*&^%$?!'; //字符池
    $key = '';
    for($i=0;$i<$length;$i++)
    {
        $key .= $pattern{mt_rand(0,35)}; //生成php随机数
    }
    return $key;
}

/**
 * 提取二维数组中某个字段的值
 */
function pick_from_2array($field, $arr) {
    $ret = [];
    foreach($arr as $key => $a){
        $ret[$key] = isset($a[$field])?$a[$field]:'';
    }
    return $ret;

}
/**
 * 二维数组根据某个字段排序
 * @param  [type] $arrUsers [description] 需要排序的数组
 * @param [type] $field     [description] 按哪个字段排序
 * @param [type] $way       [description] 排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
 */
function inge_sortArrByField($arrUsers, $field, $way = 'SORT_ASC')
{
    $sort = array(
        'direction' => $way,
        'field'     => $field,
    );
    $arrSort = array();
    foreach ($arrUsers as $uniqid => $row) {
        foreach ($row as $key => $value) {
            $arrSort[$key][$uniqid] = $value;
        }
    }
    if ($sort['direction']) {
        array_multisort($arrSort[$sort['field']], constant($sort['direction']), $arrUsers);
    }

    return $arrUsers;
}

/**
 * 返回不含前缀的数据库表数组
 *
 * @author rainfer <81818832@qq.com>
 * @param bool
 * @return array
 */
function db_get_tables($prefix = false)
{
    $db_prefix = config('database.prefix');
    $list      = \think\Db::query('SHOW TABLE STATUS FROM ' . config('database.database'));
    $list      = array_map('array_change_key_case', $list);
    $tables    = array();
    foreach ($list as $k => $v) {
        if (empty($prefix)) {
            if (stripos($v['name'], strtolower(config('database.prefix'))) === 0) {
                $tables[] = strtolower(substr($v['name'], strlen($db_prefix)));
            }
        } else {
            $tables[] = strtolower($v['name']);
        }

    }
    return $tables;
}

/**
 * 递归重组节点信息为多维数组
 * @param array
 * @param int
 * @param string
 * @param string
 * @param string
 * @return array
 */
function node_merge(&$node, $pid = 0, $id_name = 'id', $pid_name = 'pid', $child_name = '_child')
{
    $arr = array();
    foreach ($node as $v) {
        if ($v[$pid_name] == $pid) {
            $v[$child_name] = node_merge($node, $v[$id_name], $id_name, $pid_name, $child_name);
            $arr[]          = $v;
        }
    }
    return $arr;
}
/**
 * 截取待html的文本
 * @author rainfer <81818832@qq.com>
 * @param string $html
 * @param int $max
 * @param string $suffix
 * @return string;
 */
function html_trim($html, $max, $suffix = '...')
{
    $html = trim($html);
    if (strlen($html) <= $max) {
        return $html;
    }
    $non_paired_tags = array('br', 'hr', 'img', 'input', 'param'); // 非成对标签
    $html            = preg_replace('/<img([^>]+)>/i', '', $html);
    $count           = 0; // 有效字符计数(一个HTML实体字符算一个有效字符)
    $tag_status      = 0; // (0:非标签, 1:标签开始, 2:标签名开始, 3:标签名结束)
    $nodes           = array(); // 存放解析出的节点(文本节点:array(0, '文本内容', 'text', 0), 标签节点:array(1, 'tag', 'tag_name', '标签性质:0:非成对标签,1:成对标签的开始标签,2:闭合标签'))
    $segment         = ''; // 文本片段
    $tag_name        = ''; // 标签名
    for ($i = 0; $i < strlen($html); $i++) {
        $char = $html[$i]; // 当前字符
        $segment .= $char; // 保存文本片段
        if ($tag_status == 4) {
            $tag_status = 0;
        }
        if ($tag_status == 0 && $char == '<') {
            // 没有开启标签状态,设置标签开启状态
            $tag_status = 1;
        }
        if ($tag_status == 1 && $char != '<') {
            // 标签状态设置为开启后,用下一个字符来确定是一个标签的开始
            $tag_status = 2; //标签名开始
            $tag_name   = ''; // 清空标签名
            // 确认标签开启,将标签之前保存的字符版本存为文本节点
            $nodes[] = array(0, substr($segment, 0, strlen($segment) - 2), 'text', 0);
            $segment = '<' . $char; // 重置片段,以标签开头
        }
        if ($tag_status == 2) {
            // 提取标签名
            if ($char == ' ' || $char == '>' || $char == "\t") {
                $tag_status = 3; // 标签名结束
            } else {
                $tag_name .= $char; // 增加标签名字符
            }
        }
        if ($tag_status == 3 && $char == '>') {
            $tag_status = 4; // 重置标签状态
            $tag_name   = strtolower($tag_name);
            // 跳过成对标签的闭合标签
            $tag_type = 1;
            if (in_array($tag_name, $non_paired_tags)) {
                // 非成对标签
                $tag_type = 0;
            } elseif ($tag_name[0] == '/') {
                $tag_type = 2;
            }
            // 标签结束,保存标签节点
            $nodes[] = array(1, $segment, $tag_name, $tag_type);
            $segment = ''; // 清空片段
        }
        if ($tag_status == 0) {
            //echo $char.')'.$count."\n";
            if ($char == '&') {
                // 处理HTML实体,10个字符以内碰到';',则认为是一个HTML实体
                for ($e = 1; $e <= 10; $e++) {
                    if ($html[$i + $e] == ';') {
                        $segment .= substr($html, $i + 1, $e); // 保存实体
                        $i += $e; // 跳过实体字符所占长度
                        break;
                    }
                }
            } else {
                // 非标签情况下检查有效文本
                $char_code = ord($char); // 字符编码
                if ($char_code >= 224) // 三字节字符
                {
                    $segment .= $html[$i + 1] . $html[$i + 2]; // 保存字符
                    $i += 2; // 跳过下2个字符的长度
                } elseif ($char_code >= 129) // 双字节字符
                {
                    $segment .= $html[$i + 1];
                    $i += 1; // 跳过下一个字符的长度
                }
            }
            $count++;
            if ($count == $max) {
                $nodes[] = array(0, $segment . $suffix, 'text', 0);
                break;
            }
        }
    }
    $html           = '';
    $tag_open_stack = array(); // 成对标签的开始标签栈
    for ($i = 0; $i < count($nodes); $i++) {
        $node = $nodes[$i];
        if ($node[3] == 1) {
            array_push($tag_open_stack, $node[2]); // 开始标签入栈
        } elseif ($node[3] == 2) {
            array_pop($tag_open_stack); // 碰到一个结束标签,出栈一个开始标签
        }
        $html .= $node[1];
    }
    while ($tag_name = array_pop($tag_open_stack)) // 用剩下的未出栈的开始标签补齐未闭合的成对标签
    {
        $html .= '</' . $tag_name . '>';
    }
    return $html;
}

/**
 * 货币转换
 * @param float
 * @return string
 */
function long_currency($long)
{
    return sprintf('%d.%02d', intval($long / 100), intval($long % 100));
}
/**
 * 货币转换
 * @param string
 * @return float
 */
function currency_long($currency)
{
    $s = explode('.', trim($currency));
    switch (count($s)) {
        case 1:
            return $s[0] * 100;
        case 2:
            if (strlen($s[1]) == 1) {
                $s[1] .= '0';
            } else if (strlen($s[1]) > 2) {
                $s[1] = substr($s[1], 0, 2);
            }
            return $s[0] * 100 + $s[1];
    }
    return 0;
}
/**
 * 设置全局配置到文件
 *
 * @param $key
 * @param $value
 * @return boolean
 */
function sys_config_setbykey($key, $value)
{
    $file = ROOT_PATH . 'data/conf/config.php';
    $cfg  = array();
    if (file_exists($file)) {
        $cfg = include $file;
    }
    $item = explode('.', $key);
    switch (count($item)) {
        case 1:
            $cfg[$item[0]] = $value;
            break;
        case 2:
            $cfg[$item[0]][$item[1]] = $value;
            break;
    }
    return file_put_contents($file, "<?php\nreturn " . var_export($cfg, true) . ";");
}
/**
 * 设置全局配置到文件
 *
 * @param array
 * @return boolean
 */
function sys_config_setbyarr($data)
{
    $file = ROOT_PATH . 'data/conf/config.php';
    if (file_exists($file)) {
        $configs = include $file;
    } else {
        $configs = array();
    }
    $configs = array_merge($configs, $data);
    return file_put_contents($file, "<?php\treturn " . var_export($configs, true) . ";");
}
/**
 * 获取全局配置
 *
 * @param $key
 * @return array|null
 */
function sys_config_get($key)
{
    $file = ROOT_PATH . 'data/conf/config.php';
    $cfg  = array();
    if (file_exists($file)) {
        $cfg = (include $file);
    }
    return isset($cfg[$key]) ? $cfg[$key] : null;
}
/**
 * 列出本地目录的文件
 * @author rainfer <81818832@qq.com>
 * @param string $path
 * @param string $pattern
 * @return array
 */
function list_file($path, $pattern = '*')
{
    if (strpos($pattern, '|') !== false) {
        $patterns = explode('|', $pattern);
    } else {
        $patterns[0] = $pattern;
    }
    $i   = 0;
    $dir = array();
    if (is_dir($path)) {
        $path = rtrim($path, '/') . '/';
    }
    foreach ($patterns as $pattern) {
        $list = glob($path . $pattern);
        if ($list !== false) {
            foreach ($list as $file) {
                $dir[$i]['filename']   = basename($file);
                $dir[$i]['path']       = dirname($file);
                $dir[$i]['pathname']   = realpath($file);
                $dir[$i]['owner']      = fileowner($file);
                $dir[$i]['perms']      = substr(base_convert(fileperms($file), 10, 8), -4);
                $dir[$i]['atime']      = fileatime($file);
                $dir[$i]['ctime']      = filectime($file);
                $dir[$i]['mtime']      = filemtime($file);
                $dir[$i]['size']       = filesize($file);
                $dir[$i]['type']       = filetype($file);
                $dir[$i]['ext']        = is_file($file) ? strtolower(substr(strrchr(basename($file), '.'), 1)) : '';
                $dir[$i]['isDir']      = is_dir($file);
                $dir[$i]['isFile']     = is_file($file);
                $dir[$i]['isLink']     = is_link($file);
                $dir[$i]['isReadable'] = is_readable($file);
                $dir[$i]['isWritable'] = is_writable($file);
                $i++;
            }
        }
    }
    $cmp_func = create_function('$a,$b', '
        if( ($a["isDir"] && $b["isDir"]) || (!$a["isDir"] && !$b["isDir"]) ){
            return  $a["filename"]>$b["filename"]?1:-1;
        }else{
            if($a["isDir"]){
                return -1;
            }else if($b["isDir"]){
                return 1;
            }
            if($a["filename"]  ==  $b["filename"])  return  0;
            return  $a["filename"]>$b["filename"]?-1:1;
        }
        ');
    usort($dir, $cmp_func);
    return $dir;
}
/**
 * 删除文件夹
 * @author rainfer <81818832@qq.com>
 * @param string
 * @param int
 */
function remove_dir($dir, $time_thres = -1)
{
    foreach (list_file($dir) as $f) {
        if ($f['isDir']) {
            remove_dir($f['pathname'] . '/');
        } else if ($f['isFile'] && $f['filename']) {
            if ($time_thres == -1 || $f['mtime'] < $time_thres) {
                @unlink($f['pathname']);
            }
        }
    }
}
/**
 * 通过用户id获取用户名
 */
function get_username_byid($id)
{
    $res = Db::table('__USER__')->where('user_id', $id)->find();
    if ($res) {
        return $res['user_name'];
    } else {
        return '';
    }
}
/**
 * 通用列表排序函数
 * @param  string $value [description]
 * @return [type]        [description]
 */
function listorder($idtitle, $id, $order, $modelobject)
{
    foreach ($id as $key => $value) {
        $list[] = [$idtitle => $value, 'listorder' => $order[$key]];
    }
    $res = $modelobject->saveAll($list);
    return $res;
}
/**
 * 根据ID获取Term信息 传入$field参数，获取指定字段
 * @param  [type] $id   [description]
 * @param  string $field [description]
 * @return [type]       [description]
 */
function get_terminfo_by_newid($id, $field = '')
{
    $res = Loader::model('Terms')->getTermForObjectId($id);
    if ($res) {
        $res = Loader::model('Terms')->where('term_id', $res['term_id'])->find();
        if ($res) {
            if ($field == '') {
                return $res;
            } else {
                return $res[$field];
            }
        }
    }
    return '';
}


function numinput_to_num($str){
	return  $string=str_replace(',','',$str);
}

/**
 * 传入用户id获取等级信息
 * @param  [type] $uid [description]
 * @return [type]      [description]
 */
function store_get_level_by_uid($uid)
{
    $map['user_id'] = $uid;
    $level_id = Db::table('__USER__')->where($map)->value('level');
    $level_data = Db::table('__USER_LEVEL__')->where('level_id',$level_id)->find();
    if(count($level_data)) {
        return $level_data;
    } else {
        return 0;
    }
}

/**
 * 传入用户id和amount获取等级
 * @param  [type] $uid    [description]
 * @param  [type] $amount [description]
 * @return [type]         [description]
 */
function store_get_level($uid, $amount)
{
    $map['user_id'] = $uid;
    $level_id = Db::table('__USER__')->where($map)->value('level');
    $level_name = Db::table('__USER_LEVEL__')->where('level_id',$level_id)->find();
    if($level_name) {
        return $level_name;
    } else {
        return 0;
    } 
}

/**
 * 提升用户总消费额
 * @return [type] [description]
 */
function user_inc_amount($uid, $amo)
{
    $map['user_id'] = $uid;
    $res = Db::table('__USER__')->where($map)->setInc('total_amount', $amo);
    if($res) {
        return 1;
    } else {
        return 0;
    }
}



/**
 * 降低用户总消费额
 * @return [type] [description]
 */
function user_dec_amount($uid, $amo)
{
    $map['user_id'] = $uid;
    $res = Db::table('__USER__')->where($map)->setDec('total_amount', $amo);
    if($res) {
        return 1;
    } else {
        return 0;
    }
}

/**
 * 数据字典操作
 */
function dc($dictionary,$dict_value = ''){
    $query = Db::table('ig_dict_data')->where("dict_value",$dictionary);
    if($dict_value){
        return $query->where('dict_data_value',$dict_value)->limit(1)->find()['dict_value'];
    }
    return $query->select();
}
function dchtml($dictionary,$dict_data_value){
    $dict = Db::table('ig_dict_data')->where("dict_value",$dictionary)->where('dict_data_value',$dict_data_value)->select();
    if($dict){
        return $dict[0]['dict_data_name'];
    }
    return '';

}

function dc2option($dictionary,$default=''){
    $options = dc($dictionary);
    $result = '';
    foreach($options as $option){
        $result .= '<option value="'.$option['dict_data_value'].'"'.(($default==$option['dict_data_value'])?'selected>':'>').$option['dict_data_name'].'</option>';
    }
    return $result;
}



/**
 * 文件上传
 * @param unknown $name 名称
 * @param string $value
 * @param string $default
 * @param unknown $options
 * @return string
 */
function tpl_form_field_file($name, $value = '', $default = '', $options = array()) {
    global $_W;

   

	$modalID = mt_rand();
    $s = '';
   

    $s .= '
<div class="input-group ">
	<input type="text" name="'.$name.'" value="'.$value.'" class="form-control" autocomplete="off">
	<span class="input-group-btn">
		<a id="modal-994217"  href="#modal-container-'.$modalID.'" role="button" class="btn btn-default" data-toggle="modal">选择文件</a>
	</span>
	<script>
		$(function(){	$("body").append(\'<div class="modal fade" id="modal-container-'.$modalID.'" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">\'
		+\'<div class="modal-dialog">\'
		+\'	<div class="modal-content">\'
				
		+\'			<div class="modal-header">\'
		+\'				 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>\'
		+\'				<h4 class="modal-title" id="myModalLabel">\'
		+\'					选择文件\'
		+\'				</h4>\'
		+\'			</div>\'
		+\'			<div class="modal-body">\'
		+\'				<form id= "uploadForm-'.$modalID.'" action= "./index.php?s=/Admin/Upload/uploadFile" method= "post" enctype ="multipart/form-data">\'
		+\'					<input type ="file" name="upfile" style = "display:none;" onchange = "uploadFile'.$modalID.'()"/></p>\'
		+\'				<input  type = "button" class = "btn btn-primary" onclick="upfile.click()" value = "点击选择文件"/>\'							
		+\'					<div id = "filename-'.$modalID.'"></div>\'
		+\'				</form>\'


						
		+\'			</div>\'
		+\'			<div class="modal-footer">\'
		+\'				 <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> <button type="button" class="btn btn-primary" data-dismiss="modal" id = "btn-'.$modalID.'" bind-data = "" onclick = ok(this,"modal-container-'.$modalID.'","'.$name.'")>保存</button>\'
		+\'			</div>\'
				
		+\'	</div>\'
			
		+\'</div>\'
		
	+\'</div>\');
		});
		function uploadFile'.$modalID.'(){
			console.log("上传文件中...");
			$.ajax({  
				 url : "'.url("/upload/file",['action' => "uploadfile"]).'",  
				 type : "POST",  
				 data :  new FormData($("#uploadForm-'.$modalID.'")[0]),
				 processData: false,
				 contentType: false
			}).done(function(res){
				var resp = res;
				console.log(res);
				 $( "#filename-'.$modalID.'").text(resp.original);  
				 $("#btn-'.$modalID.'").attr("bind-data",resp.url);
			}).fail(function(res){
				$("#filename-'.$modalID.'").text("文件上传失败");  
			}); 
		}
		function ok(obj,container,name){
			var inputs = $("input[name=\'" + name + "\']");
			var value = $(obj).attr("bind-data");
			$(inputs[0]).val(value);
			//$("#" + "container").hide();
		}
	</script>
</div>';

    return $s;
}


/**
 * 单图上传
 * @param unknown $name 名称
 * @param string $value
 * @param string $default
 * @param unknown $options
 * @return string
 */
function tpl_form_field_image($name, $value = '', $default = '', $options = array()) {
    global $_W;
    $modalID = mt_rand();
    $s = '';


    $s .= '
<div class="input-group ">
	<input type="text" name="'.$name.'" value="'.$value.'" class="form-control" autocomplete="off">
	<span class="input-group-btn">
		<a id="modal-994217"  href="#modal-container-'.$modalID.'" role="button" class="btn btn-default" data-toggle="modal">选择文件</a>
	</span>
	<script>
		$(function(){	$("body").append(\'<div class="modal fade" id="modal-container-'.$modalID.'" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">\'
		+\'<div class="modal-dialog">\'
		+\'	<div class="modal-content">\'
				
		+\'			<div class="modal-header">\'
		+\'				 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>\'
		+\'				<h4 class="modal-title" id="myModalLabel">\'
		+\'					选择文件\'
		+\'				</h4>\'
		+\'			</div>\'
		+\'			<div class="modal-body">\'
		+\'				<form id= "uploadForm-'.$modalID.'" action= "./index.php?s=/Admin/Upload/uploadFile" method= "post" enctype ="multipart/form-data">\'
		+\'              <input type="hidden" name="action" value="uploadimage"/>\'
		+\'					<input type ="file" name="upfile" style = "display:none;" onchange = "uploadFile'.$modalID.'()"/></p>\'
		+\'				<input  type = "button" class = "btn btn-primary" onclick="upfile.click()" value = "点击选择文件"/>\'							
		+\'					<div id = "filename-'.$modalID.'"></div>\'
		+\'				</form>\'


						
		+\'			</div>\'
		+\'			<div class="modal-footer">\'
		+\'				 <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> <button type="button" class="btn btn-primary" data-dismiss="modal" id = "btn-'.$modalID.'" bind-data = "" onclick = ok(this,"modal-container-'.$modalID.'","'.$name.'")>保存</button>\'
		+\'			</div>\'
				
		+\'	</div>\'
			
		+\'</div>\'
		
	+\'</div>\');
		});
		function uploadFile'.$modalID.'(){
			console.log("上传文件中...");
			$.ajax({  
				 url : "'.url("/upload/file",['action' => "uploadimage"]).'",  
				 type : "POST",  
				 data :  new FormData($("#uploadForm-'.$modalID.'")[0]),
				 processData: false,
				 contentType: false
			}).done(function(res){
				var resp = res;
			    if(resp.state != "SUCCESS"){
			        alert(resp.state);
			        return;
			    }
				 $( "#filename-'.$modalID.'").text(resp.original);  
				 $("#btn-'.$modalID.'").attr("bind-data",resp.url);
			}).fail(function(res){
				$("#filename-'.$modalID.'").text("文件上传失败");  
			}); 
		}
		function ok(obj,container,name){
			var inputs = $("input[name=\'" + name + "\']");
			var value = $(obj).attr("bind-data");
			$(inputs[0]).val(value);
			var imgs = $("img[name=\'img" + name + "\']");
			$(imgs[0]).attr("src",value);
			//$("#" + "container").hide();
		}
		function deleteImage(elm){
		    $(elm).prev().attr("src","/static/images/nopic.jpg");
		    $(elm).parent().prev().find("input").val("");
		}
	</script>
</div>
 <div class = "input-group" style = "margin-top:.5em;">
    <img src="'.$value.'" name="img'.$name.'" onerror="this.src=\'/static/images/nopic.jpg\';this.title=\'图片未找到\'" class = "img-responsive img-thumbnail" width="150"/>
     <em class="close" style="position:absolute;top:0px;right:-14px;" title="删除这张图片" onclick="deleteImage(this)">x</em>
</div>
';

    return $s;
}
